import os.path
import traceback

import yaml
import chardet
try:
    program_yaml_paths = [r'D:\code\project_format_lianlun\config\program.yaml', # 客户机
                         r'D:\code\git\zxc\project_format_lianlun\config\program.yaml', # 本机
                         '.\config\program.yaml']
    program_yaml_path = ''
    for item in program_yaml_paths:
        if os.path.exists(item):
            program_yaml_path = item
            break

    # 检测文件编码
    with open(program_yaml_path, 'rb') as f:
        raw_data = f.read()
        result = chardet.detect(raw_data)
        encoding = result['encoding']

    with open(program_yaml_path, 'r', encoding=encoding, errors='ignore') as file:
        program_config_dict = yaml.safe_load(file)

    '''
    runtime
    '''
    # 服务和相机窗口匹配策略
    windowId = -1
    serviceStep_windowId_dict = {} # {(service_str, step_str):windowId}
    for service_str in program_config_dict['services']['services_running_list']:
        for step_str in program_config_dict['services'][service_str]['product_list']:

            # windowId += 1
            # windowId = windowId%9
            if service_str == 'p_1':
                windowId = 0
            elif service_str =='p_2':
                windowId = 1
            elif service_str =='p_3':
                windowId = 2
            else:
                windowId = 0

            serviceStep_windowId_dict[(service_str, step_str)] = windowId
    program_config_dict['ui_dict']['runtime_serviceStep_windowId_dict'] = serviceStep_windowId_dict


    # 用于服务和手动触发项匹配
    service_step_dict = {}
    for service_str in program_config_dict['services']['services_running_list']:
        step_list = []
        for step_str in program_config_dict['services'][service_str]['product_list']:
            step_list.append(step_str)
        service_step_dict[service_str] = step_list
    program_config_dict['ui_dict']['runtime_service_step_dict'] = service_step_dict



    # 逐行计算运行时间
    if program_config_dict['is_use_line_profiler']:
        from line_profiler import LineProfiler
        profiler = LineProfiler()
    else:
        def empty_decorator(func):
            return func
        profiler = empty_decorator


except:
    print(traceback.format_exc())